package me.zk.practice1.s;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhangkai
 * @date 2023/7/15 13:21
 */
public class LS_Offer_32_3 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        LinkedList<List<Integer>> res = new LinkedList<>();
        queue.add(root);
        boolean isLeft = false;
        while (!queue.isEmpty()) {
            LinkedList<Integer> tmp = new LinkedList<>();
            for (int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                if (res.size() % 2 ==0) {
                    tmp.addLast(node.val);
                } else {
                    tmp.addFirst(node.val);
                }
                if (node.left!=null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }

            }
            isLeft = !isLeft;
            res.add(tmp);
        }
        return res;
    }
}
